import { UIComponent, UIMgr } from '../../../Framework/Scripts/Managers/UIMgr';
import { _decorator, Component, Node, JsonAsset, Texture2D, EventTouch, Vec2, UITransform, math, Rect, Game, Vec3, Button, ProgressBar, Label, director, SpriteFrame, RenderTexture, Sprite, view, Size, LightProbeGroup } from 'cc';
import { GameApp } from '../GameApp';
import ClockCtrl from '../fight/clockCtrl';
import { joyStick2 } from '../fight/joyStick2';
import { constant, SkillType } from '../constant';
import { EventMgr } from '../../../Framework/Scripts/Managers/EventMgr';
import { Vector3 } from '../../../Framework/Scripts/Utils/Vector3';
import { UserData } from '../userData/UserData';
import { SoundMgr } from '../../../Framework/Scripts/Managers/SoundMgr';
import { ResMgr } from '../../../Framework/Scripts/Managers/ResMgr';

const { ccclass, property } = _decorator;

@ccclass('UIstart_UICtrl')
export class UIstart_UICtrl extends UIComponent {
    private sp = null
    private renderTex: RenderTexture = null
    private minMapNode: Node = null
    private startSkillTouch = {
        pos: new Vec3(0, 0, 0),
        width: 100,
        height: 100,


    }


    private isOnTouch: boolean = false
    private time: number = 0.65
    private nowTime: number = 0

    private ontouchPos: Vec3 = new Vec3()//点击摇杆技能时候初始坐标

    private allSkillEnabled: boolean = false
    private skillTouch: Node = null
    private skillJoyStick: Node = null;//技能摇杆

    private skillJoyStickTs: joyStick2 = null;

    private isUseSkillJoyStick: boolean = false//技能摇杆正在使用 可以去掉
    private nowSkillName: string = ""//当前正在使用摇杆的技能
    private ProgressBar: ProgressBar = null
    private bulidHpLabel: Label = null

    private bulidHp: ProgressBar = null

    private outUI: Node = null

    private skillNode = {
        skill1: null,
        skill2: null,
        skill3: null,
        skill4: null,





    };

    private skillCDMgr = {
        skill1: false,
        skill2: false,
        skill3: false,
        skill4: false,
    }


    private skillType = {
        skill1: false,
        skill2: false,
        skill3: false,
        skill4: false,
    }

    private allSkillBtnEnabled(name: string, b: boolean) {
        this.allSkillEnabled = b
    }
    private subEnemyCount(name: string, data) {

        // { skillEnemyCount: this.skillEnemyCount, enemyCount: this.enemyCount }

        this.ProgressBar.progress = data.skillEnemyCount / data.enemyCount

        this.ProgressBar.node.getChildByName("level").getComponent(Label).string = data.skillEnemyCount + "/" + Math.floor(data.enemyCount)

    }

    private subBuildHp(name: string, data) {
        if (!this.bulidHp) {
            return
        }

        if (data.nowHP <= 0) {
            if (this.bulidHp) {
                this.bulidHp.progress = 0
            }


            this.bulidHpLabel.string = data.startHP + "/" + 0
            return
        }
        const bfb: number = data.nowHP / data.startHP
        if (bfb >= 0) {
            try {
                if (this.bulidHp) {
                    this.bulidHp.progress = bfb

                }
            } catch (error) {


                console.log("更新血条失败===========", error);

            }

        } else {
            if (this.bulidHp) {
                this.bulidHp.progress = 0
            }

        }

        try {
            if (this.bulidHp) {
                this.bulidHpLabel.string = data.startHP + "/" + Math.floor(data.nowHP)

            }

        } catch (error) {
            console.log("血条没有===================", error);

        }
    }
    onLoad() {
        SoundMgr.Instance.stopBgMusic()
        SoundMgr.Instance.playBgMusic(ResMgr.Instance.getAsset("Sounds", "bgm2"), true)

        GameApp.Instance.isBack = false

        const b: number = view.getVisibleSize().height

        this.ViewNode("top").position = new Vec3(this.ViewNode("top").position.x, (b / 2) - this.ViewNode("top").getComponent(UITransform).height / 2, 0)

        const buildingHp: number = constant.buildData.hp.level * constant.buildData.hp.add + 200
        this.outUI = this.ViewNode("outUI")
        this.AddButtonListener("top/showOutUI", this, () => {
            this.outUI.active = true
            director.pause()

        })
        this.AddButtonListener("outUI/colse", this, () => {
            this.outUI.active = false
            director.resume()

        })
        this.AddButtonListener("outUI/outGame", this, () => {

            SoundMgr.Instance.stopBgMusic()
            GameApp.Instance.isBack = false
            GameApp.Instance.stopTimer()

            GameApp.Instance.delAll()
            UIMgr.Instance.DestroyUIView(this.node.name)
            GameApp.Instance.enterGame()

        })
        this.AddButtonListener("outUI/set", this, () => {
            UIMgr.Instance.showUIView("set")
            console.log("点击了设置");

        })

        this.outUI.active = false
        this.bulidHp = this.ViewNode("top/bulidHP").getComponent(ProgressBar)
        this.bulidHpLabel = this.ViewNode("top/bulidHP/level").getComponent(Label)
        this.bulidHpLabel.string = buildingHp + "/" + buildingHp

        this.minMapNode = this.ViewNode("top/Mask/minMap")
        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.stopSkillCd, this.stopSkillCd, this);
        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.skillFire, this.skillFire, this);

        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.subBuildHp, this.subBuildHp, this);
        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.subEnemyCount, this.subEnemyCount, this);


        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.upGameStartTop, this.upGameStartTop, this);


        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.allSkillBtnEnabled, this.allSkillBtnEnabled, this);
        this.skillNode.skill1 = this.ViewNode("skill_root/skill1")
        this.skillNode.skill2 = this.ViewNode("skill_root/skill2")
        this.skillNode.skill3 = this.ViewNode("skill_root/skill3")
        this.skillNode.skill4 = this.ViewNode("skill_root/skill4")



        this.ViewNode("top/startGameLevel/levelNum").getComponent(Label).string = "第" + GameApp.Instance.level + "关"


        //不能用的技能置灰

        if (GameApp.Instance.playerData["skills"]["skill1"]["minLevel"] > GameApp.Instance.level) {
            console.log("技能最小" + GameApp.Instance.playerData["skills"]["skill1"]["minLevel"]);

            this.skillNode.skill1.getChildByName("Label").active = false
            this.skillNode.skill1.getChildByName("mask").active = false
            this.skillNode.skill1.getChildByName("hui").active = true
        }
        if (GameApp.Instance.playerData["skills"]["skill2"]["minLevel"] > GameApp.Instance.level) {
            console.log("技能最小" + GameApp.Instance.playerData["skills"]["skill2"]["minLevel"]);
            this.skillNode.skill2.getChildByName("Label").active = false
            this.skillNode.skill2.getChildByName("mask").active = false
            this.skillNode.skill2.getChildByName("hui").active = true
        }

        if (GameApp.Instance.playerData["skills"]["skill3"]["minLevel"] > GameApp.Instance.level) {
            console.log("技能最小" + GameApp.Instance.playerData["skills"]["skill3"]["minLevel"]);
            this.skillNode.skill3.getChildByName("Label").active = false
            this.skillNode.skill3.getChildByName("mask").active = false
            this.skillNode.skill3.getChildByName("hui").active = true
        }
        if (GameApp.Instance.playerData["skills"]["skill4"]["minLevel"] > GameApp.Instance.level) {
            console.log("技能最小" + GameApp.Instance.playerData["skills"]["skill4"]["minLevel"]);

            this.skillNode.skill4.getChildByName("Label").active = false
            this.skillNode.skill4.getChildByName("mask").active = false
            this.skillNode.skill4.getChildByName("hui").active = true
        }
        this.skillJoyStick = this.ViewNode("skillTouch/joyStick2")
        this.skillTouch = this.ViewNode("skillTouch")
        this.startSkillTouch.pos = this.skillTouch.getPosition()
        this.startSkillTouch.width = this.skillTouch.getComponent(UITransform).width
        this.startSkillTouch.height = this.skillTouch.getComponent(UITransform).height

        this.ProgressBar = this.ViewNode("top/ProgressBar").getComponent(ProgressBar)
        this.skillJoyStickTs = this.skillJoyStick.getComponent(joyStick2)
        //查看技能瞬发
        const skillConfig = GameApp.Instance.playerData["skills"]



        for (let key in this.skillType) {

            if (skillConfig[key]["type"] == SkillType.Instant) {
                this.skillType[key] = false
            } else {
                this.skillType[key] = true
            }









            // for (let key2 in skillConfig) {
            //     if (skillConfig[key2]["btnName"] == key) {
            //         if (skillConfig[key2]["type"] == SkillType.Instant) {
            //             this.skillType[key] = false
            //         } else {
            //             this.skillType[key] = true
            //         }

            //     }
            // }






        }

        this.upGameStartTop("",null)

    }
    private upGameStartTop(name: string, data) {
        this.ViewNode("top/gold/Label").getComponent(Label).string ="金币："+ UserData.Instance.localData["gold"]
        this.ViewNode("top/ore/Label").getComponent(Label).string = "宝石："+UserData.Instance.localData["ore"]

    }
    start() {
        const b: Size = view.getVisibleSize()
        this.sp = null;
        this.renderTex = null;
        this.sp = new SpriteFrame();
        this.renderTex = new RenderTexture();
        this.renderTex.reset({
            width: b.width,
            height: b.height,



        });
        GameApp.Instance.minMapCamer.targetTexture = this.renderTex;
        this.sp.texture = this.renderTex;
        this.minMapNode.getComponent(UITransform).width = b.width / 3
        this.minMapNode.getComponent(UITransform).height = b.height / 3
        this.minMapNode.getComponent(Sprite).spriteFrame = this.sp;
    }

    private skillShow(skillName: string, isUseSkillJoyStick: boolean) {

        if (this.skillCDMgr[skillName] == true) {
            this.nowSkillName = ""
            return
        }
        if (GameApp.Instance.playerTs.isDie) {
            //玩家死亡禁止使用技能按钮
            return
        }
        this.nowSkillName = skillName
        if (this.allSkillEnabled && !GameApp.Instance.playerData["skills"][this.nowSkillName]["isAlltimeUse"]) {
            //   console.log("禁止使用任何技能");
            this.nowSkillName = ""
            return



        }
        //包围盒判断

        //是否使用摇杆
        if (isUseSkillJoyStick) {
            this.isOnTouch = true

            GameApp.Instance.playerTs.showWarming(GameApp.Instance.playerData["skills"][this.nowSkillName]["rangeType"], this.nowSkillName)
            if (GameApp.Instance.playerTs.warmingNode) {
                //可以找当前的敌人
                if (GameApp.Instance.playerTs.nowEnemy) {

                    const VecDifference: Vec3 = Vector3.sub(GameApp.Instance.playerTs.nowEnemy.worldPosition, GameApp.Instance.player.worldPosition).normalize().negative()
                    const d: number = Math.atan2(VecDifference.x, VecDifference.z)
                    const r: number = d / Math.PI * 180
                    GameApp.Instance.playerTs.warmingNode.eulerAngles = new Vec3(0, r, 0)
                } else {

                    GameApp.Instance.playerTs.warmingNode.eulerAngles = GameApp.Instance.player.eulerAngles

                }


            }
            this.skillJoyStick.active = true
            this.skillJoyStick.setPosition(this.skillNode[this.nowSkillName].position)
            this.isUseSkillJoyStick = true

        }

    }





    private touchStart(event: EventTouch) {




        const pos: Vec2 = event.getUILocation()
        this.ontouchPos = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(pos.x, pos.y, 0))
        for (let key in this.skillNode) {
            const box: math.Rect = this.skillNode[key].getComponent(UITransform).getBoundingBoxToWorld()
            if (box.contains(pos)) {



                switch (key) {

                    case "skill1":

                        if (GameApp.Instance.playerData["skills"]["skill1"]["minLevel"] <= GameApp.Instance.level) {
                            this.skillShow(key, this.skillType.skill1)

                        } else {
                            GameApp.Instance.show_tip(GameApp.Instance.playerData["skills"]["skill1"]["name"] + " 需要在第" + GameApp.Instance.playerData["skills"]["skill1"]["minLevel"] + "关开启")


                        }

                        break;

                    case "skill2":
                        if (GameApp.Instance.playerData["skills"]["skill2"]["minLevel"] <= GameApp.Instance.level) {
                            this.skillShow(key, this.skillType.skill2)

                        } else {
                            GameApp.Instance.show_tip(GameApp.Instance.playerData["skills"]["skill2"]["name"] + " 需要在第" + GameApp.Instance.playerData["skills"]["skill2"]["minLevel"] + "关开启")

                        }

                        break;


                    case "skill3":
                        if (GameApp.Instance.playerData["skills"]["skill3"]["minLevel"] <= GameApp.Instance.level) {
                            this.skillShow(key, this.skillType.skill3)

                        } else {
                            GameApp.Instance.show_tip(GameApp.Instance.playerData["skills"]["skill3"]["name"] + " 需要在第" + GameApp.Instance.playerData["skills"]["skill3"]["minLevel"] + "关开启")

                        }
                        break;

                    case "skill4":
                        if (GameApp.Instance.playerData["skills"]["skill4"]["minLevel"] <= GameApp.Instance.level) {
                            this.skillShow(key, this.skillType.skill4)

                        } else {
                            GameApp.Instance.show_tip(GameApp.Instance.playerData["skills"]["skill4"]["name"] + " 需要在第" + GameApp.Instance.playerData["skills"]["skill4"]["minLevel"] + "关开启")

                        }
                        break;

                    default:
                        break;
                }
                break
            }
        }



    }
    private touchMove(event: EventTouch) {
        if (this.isOnTouch) {
            return
        }

        //加个延时
        if (this.skillJoyStick.active == true && this.isUseSkillJoyStick) {
            const pos: Vec2 = event.getUILocation()
            const newPos: Vec3 = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(pos.x, pos.y, 0))
            const len: number = Vector3.sub(newPos, this.ontouchPos).lengthSqr()

            if (len > 300 * 300) {
                console.log("len:" + len);
                this.ontouchPos = newPos
                this.skillJoyStick.setPosition(newPos)
            }
            const d: number = this.skillJoyStickTs.touchMove(event.getLocation())
            if (GameApp.Instance.playerTs.warmingNode)



                GameApp.Instance.playerTs.warmingNode.eulerAngles = new Vec3(0, d - 90, 0)





        }
    }

    public stopSkillCd(name: string, skillName: string) {
        if (skillName) {


            this.stopCD(skillName)
        } else {
            console.log("定制所有cd");
            this.stopALlCD()
        }
    }
    public stopALlCD() {
        for (let key in this.skillCDMgr) {
            this.stopCD(key)
        }
    }
    //技能冷却实际结束
    public stopCD(skill_name) {
        this.skillCDMgr[skill_name] = false


        const ts: ClockCtrl = this.skillNode[skill_name].getComponent(ClockCtrl)
        if (ts) {

            ts.stopClockAction()

        }
    }
    //摇杆类的技能释放
    private skillFire(name: string, skill_name: string) {
        if (this.allSkillEnabled && !GameApp.Instance.playerData["skills"][skill_name]["isAlltimeUse"]) {
            //   console.log("禁止使用任何技能2");
            this.nowSkillName = ""
            return
        }
        this.nowSkillName = skill_name
        //玩家组件调用 skill_Name对应技能

        GameApp.Instance.playerData["skills"][skill_name]["skillFunCB"]()//在表里直接调用

        // const tsName:string=GameApp.Instance.playerData["tsName"]
        // console.log("ts名字：",tsName);

        // GameApp.Instance.player.getComponent(tsName).restSkill(this.nowSkillName)
        //............


        this.isUseSkillJoyStick = false
        this.skillCDMgr[skill_name] = true
        const ts: ClockCtrl = this.skillNode[skill_name].getComponent(ClockCtrl)
        if (ts) {

            //冷却时间随玩家表来
            ts.startClockAction(GameApp.Instance.playerData["skills"][skill_name]["cd"], () => {
                this.skillCDMgr[skill_name] = false
                ts.stopClockAction()
            })
        }

        this.nowSkillName = ""
    }
    private touchEnd(event: EventTouch) {





        this.skillTouch.setPosition(this.startSkillTouch.pos)
        this.skillTouch.getComponent(UITransform).width = this.startSkillTouch.width
        this.skillTouch.getComponent(UITransform).height = this.startSkillTouch.height
        GameApp.Instance.playerTs.hidWarming()
        this.skillJoyStick.active = false

        if (this.nowSkillName == "") {
            return
        }
        this.skillFire("", this.nowSkillName)
        this.skillJoyStickTs.onEnd()//摇杆复位



    }


    private skillToushOpen(b: boolean) {
        if (b) {




            this.skillTouch.on(Node.EventType.TOUCH_START, this.touchStart, this);
            this.skillTouch.on(Node.EventType.TOUCH_MOVE, this.touchMove, this);
            this.skillTouch.on(Node.EventType.TOUCH_END, this.touchEnd, this);
            this.skillTouch.on(Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
        } else {

            this.skillTouch.off(Node.EventType.TOUCH_START, this.touchStart, this);
            this.skillTouch.off(Node.EventType.TOUCH_MOVE, this.touchMove, this);
            this.skillTouch.off(Node.EventType.TOUCH_END, this.touchEnd, this);
            this.skillTouch.off(Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
        }
    }

    onEnable() {

        this.skillToushOpen(true)
    }

    onDisable() {
        this.skillToushOpen(false)


    }

    onDestroy() {
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.subEnemyCount, this.subEnemyCount, this);
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.stopSkillCd, this.stopSkillCd, this);
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.skillFire, this.skillFire, this);
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.subBuildHp, this.subEnemyCount, this);
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.upGameStartTop, this.upGameStartTop, this);

        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.allSkillBtnEnabled, this.allSkillBtnEnabled, this);
    }



    update(dt: number) {
        if (this.isOnTouch) {
            this.nowTime += dt
            if (this.nowTime >= this.time) {


                this.skillTouch.setPosition(0, 0, 0)
                this.skillTouch.getComponent(UITransform).width = 1080
                this.skillTouch.getComponent(UITransform).height = 1920
                this.isOnTouch = false
                this.nowTime = 0
            }
        }

    }
}


